package com.babel.util.lide;

import org.bouncycastle.util.encoders.Base64;

/**
 * Byte，String工具类
 * @author lyj
 * @date 2017年5月17日---上午11:47:52
 */
public class ByteUtil {

    /**
     * 字节转换成16进制表示字符串
     * @param b
     * @return
     */
    public static String byte2HexStr(byte[] b) {
	String hs = "";
	String stmp = "";
	for (int n = 0; n < b.length; n++) {
	    stmp = (Integer.toHexString(b[n] & 0XFF));
	    if (stmp.length() == 1)
		hs = hs + "0" + stmp;
	    else
		hs = hs + stmp;
	}
	return hs.toUpperCase();
    }

    /**
     * 十六进制字符串转字节数组
     * 
     * @param s 十六进制字符串
     * @return
     */
    public static byte[] hex2bytes(String s) {
	int len = s.length();
	byte[] data = new byte[len / 2];
	for (int i = 0; i < len; i += 2) {
	    data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
	}
	return data;
    }

    /**
     * 字节通过base64转码成字符串
     * @param b
     * @return
     */
    public static String base64Encode(byte[] b) {
	return new String(Base64.encode(b));
    }

    /**
     * 字符串通过base64解码成字节
     * @param str
     * @return
     * @throws Base64DecodingException
     */
    public static byte[] base64decode(String str) {
	return Base64.decode(str);
    }

    /**
     * 二进制数组转换为字符串表示
     * @param byteArray
     * @return
     */
    public static String bytetoString(byte[] byteArray) {
	String result = "";
	char temp;

	int length = byteArray.length;
	for (int i = 0; i < length; i++) {
	    temp = (char) byteArray[i];
	    result += temp;
	}
	return result;
    }

}
